import { defineStore } from 'pinia'
import request from '@/utils/request'
import {updateUser} from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLogin: false,
    userInfo: null,
    accessToken: '',
    refreshToken: '',
    deliveryFeeRatio: 0  // 配送费与实付金额的比率
  }),
  getters: {
    // 获取用户昵称，如果未登录则返回默认值
    nickname: (state) => state.userInfo?.nickname || '游客',
    // 获取用户头像，如果未登录则返回默认头像
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    // 判断用户是否已登录
    loggedIn: (state) => state.isLogin && state.accessToken
  },
  actions: {
    // 登录操作
    login() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            this.wxLogin(loginRes.code)
              .then(resolve)
              .catch(reject)
          },
          fail: reject
        })
      })
    },
    // 微信登录
    async wxLogin(code) {
      try {
        const { data } = await request({
          url: '/wechat/wxLogin',
          method: 'POST',
          data: { code }
        })
        this.isLogin = true
        this.userInfo = data.userInfo
        this.accessToken = data.accessToken
        this.refreshToken = data.refreshToken
        this.deliveryFeeRatio = data.deliveryFeeRatio || 0
        // 保存登录状态到本地存储
        uni.setStorageSync('accessToken', this.accessToken)
        uni.setStorageSync('refreshToken', this.refreshToken)
        uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
        uni.setStorageSync('deliveryFeeRatio', this.deliveryFeeRatio)
        
        // 如果是新用户，显示欢迎提示和优惠券发放信息
        if (data.isNewUser) {
          setTimeout(() => {
            uni.showToast({
              title: '欢迎新用户！',
              icon: 'none',
              duration: 3000
            })
          }, 1000)
        }
        
        return data.userInfo
      } catch (error) {
        console.error('微信登录失败:', error)
        throw error
      }
    },
    // 退出登录
    logout() {
      this.isLogin = false
      this.userInfo = null
      this.accessToken = ''
      this.refreshToken = ''
      this.deliveryFeeRatio = 0
      // 清除本地存储的登录状态
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('deliveryFeeRatio')
    },
    // 初始化用户状态，从本地存储恢复登录状态
    async initUserState() {
      const accessToken = uni.getStorageSync('accessToken')
      const refreshToken = uni.getStorageSync('refreshToken')
      const userInfoStr = uni.getStorageSync('userInfo')
      const deliveryFeeRatio = uni.getStorageSync('deliveryFeeRatio')
      
      if (accessToken && refreshToken && userInfoStr) {
        console.log('从本地存储恢复登录状态')
        try {
          this.accessToken = accessToken
          this.refreshToken = refreshToken
          this.userInfo = JSON.parse(userInfoStr)
          this.deliveryFeeRatio = deliveryFeeRatio || 0
          this.isLogin = true
          return true // 返回登录状态
        } catch (e) {
          console.error('Failed to parse user info:', e)
          this.logout()
          return false
        }
      } else {
        console.log('没有找到本地存储的登录状态，需要用户手动登录')
        return false // 需要用户手动登录
      }
    },
    // token自动刷新
    async refreshTokenIfNeeded() {
      if (!this.refreshToken) return false
      try {
        const { data } = await request({
          url: '/wechat/refreshToken',
          method: 'POST',
          data: { refreshToken: this.refreshToken }
        })
        this.accessToken = data.accessToken
        this.refreshToken = data.refreshToken
        uni.setStorageSync('accessToken', this.accessToken)
        uni.setStorageSync('refreshToken', this.refreshToken)
        return true
      } catch (e) {
        this.logout()
        return false
      }
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      // 调用api/user.js中的updateUser方法将用户信息更新到服务器
      updateUser(this.userInfo.id, this.userInfo)
        .then(() => {
          // 更新成功后保存到本地存储
          uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
        })
        .catch(err => {
          console.error('更新用户信息失败:', err)
        })
    }
  }
})